﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using orz.mouxianyu.Extensions.ToolClass;
using Serilog;

namespace orz.mouxianyu.Extensions.Exceptions
{
    public class ErrorWrappingMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<ErrorWrappingMiddleware> _logger;

        public ErrorWrappingMiddleware(RequestDelegate next, ILogger<ErrorWrappingMiddleware> logger)
        {
            _next = next;
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next.Invoke(context);
            }
            catch (Exception ex)
            {
                //_logger.LogError(EventIds.GlobalException, ex, ex.Message);
                Log.Error(ex, ex.Message);
                context.Response.StatusCode = 500;

                StringBuilder bf = new StringBuilder();
                ex.FlattenHierarchy().ToList().ForEach(x =>bf.Append("Error:"+x.Message) );
                if (!context.Response.HasStarted)
                {
                    context.Response.ContentType = "application/json";

                    var response = new ApiResponse(context.Response.StatusCode,bf.ToString());

                    var json = JsonConvert.SerializeObject(response);

                    await context.Response.WriteAsync(json);
                }
            }

           
        }
    }
}
